import React, {useEffect} from 'react'
import {
  unmountComponentAtNode, render, createPortal,
} from 'react-dom'
import ReactDOM from 'react-dom/client'
import {message} from 'antd'
import styles from './message.module.scss'

interface MessageProps {
  children: React.ReactNode | string | boolean | number;
  type: "error" | "warning" | "success" | "info";
  onClose: () => void;
  time: number;
}

const Message = (props: MessageProps) => {
  const {children, type, onClose, time} = props
  useEffect(() => {
    const t = setTimeout(onClose, time | 3000)
    return () => {
      t && clearTimeout(t)
    }
  }, [])
  return (
    <div className={styles.alert}>
      <div className={styles.flex_1}>
        {children || '错误信息'}
      </div>
    </div>
  )
}
// 创建挂在 DOM
const getContainer = () => {
  const container = document.querySelector('#customMessageWrapper')
  if ( !container ) {
      const _container = document.createElement('div')
      _container.id = 'customMessageWrapper'
      _container.className = `fixed flex flex-col gap-4 top-0 items-center py-5 left-1/2 -translate-x-1/2`
      document.body.appendChild(_container)
      return _container
  }
  return container
}
//公用message方法
const _message = (type: string) => (props: any) => {
  const container = getContainer();
  const _dom = document.createElement("div");
  /* React18 新版 */
  const _domRoot = ReactDOM.createRoot(_dom)
  container.appendChild(_dom);
  // 移除DOM元素
  const hanldeClose = () => {
    // unmountComponentAtNode(_dom);
    _domRoot.unmount()
    container.removeChild(_dom);
  };
  // setTimeout(() => {
  //   hanldeClose()
  // }, 1000)


  /* React17 旧版 */
  // render(
  //     <Message
  //         {...props}
  //         type={type}
  //         onClose={hanldeClose}
  //     />,
  //     _dom
  // );
  _domRoot.render(
    <Message
      {...props}
      type={type}
      onClose={hanldeClose}
    />
  )
};
const error = _message("error");
const warning = _message("warning");
const success = _message("success");
const info = _message("info");

export {
  error, warning, success, info
}







export default function MessageWrap() {
  
  return (
    <div
      className={styles.message}
    >
      <div 
        onClick={() => {
          // message.success('antd message for success, 100 seconds', 100);
          success({content : '这是一条信息消息提示'})
        }}
      >
        <button>点击弹出 Message 信息</button>
      </div>
      
    </div>
  )
}
